package com.xingyang.component;

import com.xingyang.config.SmsConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * 著名信仰,愿景：让技术不再难学
 **/
@Component
@Slf4j
public class Syscomponent {

    /*
    * 发送地址
    * */
    private  static final String URL_TEMPLATE="https://jmsms.market.alicloudapi.com/sms/send?mobile=%s&templateld=%s&value=%s";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SmsConfig smsConfig;


    @Async("threadPoolTaskExecutor")
    public void send(String to, String templateId, String value) {

        String url = String.format(URL_TEMPLATE, to, templateId, value);

        HttpHeaders headers = new HttpHeaders();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.set("Authorization", "APPCODE " + smsConfig.getAppCode());

        HttpEntity<String> entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

        log.info("url={},body={}", url, response.getBody());
        if (response.getStatusCode() == HttpStatus.OK) {
            log.info("发送短信成功,响应信息:{}", response.getBody());
        } else {
            log.error("发送短信失败,响应信息:{}", response.getBody());
        }

    }

}
